package it.polimi.registration.business.weather;

import it.polimi.registration.business.security.entity.Forecast;
import it.polimi.registration.business.security.entity.WeatherType;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.inject.Inject;

import org.json.JSONArray;
import org.json.JSONObject;

public class ForecastFactory {
	
	private static final String URL = "http://api.openweathermap.org/data/2.5/forecast/daily?units=metric&cnt=16&q=";

	private String url;
	private Forecast f;

	public ForecastFactory(Forecast f) throws Exception {
		this.f = f;
		this.url = URL + f.getOwner().getLocation();

		this.update();
	}

	private void update() throws Exception {
		String result = readJsonFromURL(this.url);
		JSONObject jsonObject = new JSONObject(result);

		Calendar d = f.getOwner().getDate();
		Calendar g = new GregorianCalendar(d.get(Calendar.YEAR),d.get(Calendar.MONTH),d.get(Calendar.DAY_OF_MONTH),17,00);
		g.setTimeZone(TimeZone.getTimeZone("GMT"));
		long dateTimeToGet = g.getTime().getTime()/1000;
		
		Calendar now = new GregorianCalendar();
		
		JSONArray list = jsonObject.getJSONArray("list");
		JSONObject temp;
		JSONArray weather;
		int weather_id = 0;
		int confidence = 0;
		
		int i = 0;
		for(i=0; i<list.length(); i++) {
			temp = list.getJSONObject(i);
			if(temp.has("dt") && temp.getLong("dt") == dateTimeToGet) {
				weather = temp.getJSONArray("weather");
				weather_id = weather.getJSONObject(0).getInt("id");
				confidence = 16 - i;
				break;
			}				
		}
		
		f.setConfidence(16 + (int)(now.getTime().getTime() - d.getTime().getTime())/86400000);
		if(weather_id == 800 || weather_id == 801 || weather_id == 802)
			f.setType(WeatherType.Sunny);
		else
			f.setType(WeatherType.Bad);
		f.setDate(now);
	}
	
	private String readJsonFromURL(String urlString) throws Exception {
	    BufferedReader reader = null;
	    try {
	        URL url = new URL(urlString);
	        reader = new BufferedReader(new InputStreamReader(url.openStream()));
	        StringBuffer buffer = new StringBuffer();
	        int read;
	        char[] chars = new char[1024];
	        while ((read = reader.read(chars)) != -1)
	            buffer.append(chars, 0, read); 

	        return buffer.toString();
	    } finally {
	        if (reader != null)
	            reader.close();
	    }
	}
}
